package com.chcit.mobile.mvp.receive.fragment.pack.child;

import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.chcit.custom.view.loader.QuickLoader;
import com.chcit.custom.view.spinner.DropDownMenu;
import com.chcit.custom.view.text.one.SuperTextView;
import com.chcit.mobile.R;
import com.chcit.mobile.app.base.ScanFragment;
import com.chcit.mobile.app.utils.TimeDialogUtil;
import com.chcit.mobile.di.component.DaggerScanPackageComponent;
import com.chcit.mobile.helper.HttpClientHelper;
import com.chcit.mobile.mvp.common.contract.ScanPackageContract;
import com.chcit.mobile.mvp.common.model.MenuTypeEnum;
import com.chcit.mobile.mvp.common.presenter.ScanPackagePresenter;
import com.chcit.mobile.mvp.receive.Entity.AsnPackageBean;
import com.chcit.mobile.mvp.receive.adpter.AsnPackageAdapter;
import com.chcit.mobile.mvp.receive.api.QueryListInput;
import com.jess.arms.di.component.AppComponent;
import com.xuexiang.xui.widget.toast.XToast;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;

public class SecondPagerFragment extends ScanFragment<ScanPackagePresenter> implements ScanPackageContract.View {

    @BindView(R.id.rv_check_receive_pakcageInfo)
    RecyclerView rvCheckReceivePakcageInfo;
    @BindView(R.id.ddm_check_receive_date)
    DropDownMenu mDropDownMenu;
    private MenuTypeEnum type;
    private SuperTextView tvDateFrom;
    private SuperTextView tvDateTo;
    private AsnPackageAdapter doneAsnPackageAdapter;
    List<AsnPackageBean> doneAsnPackageBeanList = new ArrayList<>();
    private AsnPackageBean checkAsnPackageBean;
    private String headers[] = {"选择日期"};
    public static Fragment newInstance(MenuTypeEnum type) {

        return new SecondPagerFragment(type);
    }
    public SecondPagerFragment(MenuTypeEnum type) {
        this.type = type;
    }

    @Override
    protected void onBarcodeEventSuccess(String barcodeData) {
       scrollToPostion(new AsnPackageBean(barcodeData));
    }

    private void scrollToPostion(AsnPackageBean asnPackageBean) {
        int index = doneAsnPackageBeanList.indexOf(asnPackageBean);
        if(index>-1){
            doneAsnPackageAdapter.setCheckedPosition(index);
            rvCheckReceivePakcageInfo.scrollToPosition(index);
        }
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerScanPackageComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    public void setCheckAsnPackageBean(AsnPackageBean checkAsnPackageBean) {
        this.checkAsnPackageBean = checkAsnPackageBean;
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_check_receive_second, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        initDoneRecycleView();
        initDropDownMenu();

    }

    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading() {
        QuickLoader.showLoading(mContext);
    }

    @Override
    public void hideLoading() {
        QuickLoader.stopLoading();
    }


    @Override
    public void showMessage(@NonNull String message) {

    }

    @Override
    public void launchActivity(@NonNull Intent intent) {

    }


    @Override
    public void killMyself() {

    }
    private void initDropDownMenu() {
        final List<View> popupViews = new ArrayList<>();
        //日期选择
        final View dateView = getLayoutInflater().inflate(R.layout.pop_date, null);
        tvDateTo = dateView.findViewById(R.id.pop_date_drive);
        tvDateFrom = dateView.findViewById(R.id.pop_date_from);
        TextView ok = dateView.findViewById(R.id.ok);
        tvDateFrom.setCenterString(TimeDialogUtil.getBeforeDay(0));
        tvDateFrom.setOnClickListener(v -> TimeDialogUtil.showDatePickerDialog(getActivity(), 3, s->tvDateFrom.setCenterString(s), 0));
        tvDateTo.setOnClickListener(v -> TimeDialogUtil.showDatePickerDialog(getActivity(), 3, s->tvDateTo.setCenterString(s), 0));
        tvDateFrom.setOnClickListener(new View.OnClickListener() {
            Calendar calendar = Calendar.getInstance();
            @Override
            public void onClick(View v) {
                TimeDialogUtil.showDatePickerDialog(getActivity(), 3,
                        s->{
                            tvDateFrom.setCenterString(s);
                            ok.performClick();
                        },
                        0,calendar);
            }
        });
        tvDateTo.setOnClickListener(new View.OnClickListener() {
            Calendar calendar = Calendar.getInstance();
            @Override
            public void onClick(View v) {
                TimeDialogUtil.showDatePickerDialog(getActivity(), 3, s->{
                    tvDateTo.setCenterString(s);
                    ok.performClick();
                }, 0,calendar);


            }
        });

        ok.setOnClickListener(v -> {
            StringBuffer text = new StringBuffer();
            if(!tvDateFrom.getCenterString().isEmpty()){
                text.append("开始日期：");
                text.append(tvDateFrom.getCenterString()) ;
            }
            if(!tvDateTo.getCenterString().isEmpty()){
                text .append("\n结束日期："+ tvDateTo.getCenterString());
            }

            mDropDownMenu.setTabText(text==null? headers[0] : text.toString());
            mDropDownMenu.closeMenu();
            queryData();
        });
        popupViews.add(dateView);
        final TextView contentView = new TextView(getContext());
        contentView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        contentView.setText("");
        //contentView.setBackgroundColor(getResources().getColor(R.color.gray));
        contentView.setGravity(Gravity.CENTER);
        contentView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
        final List<String> list = Collections.singletonList("开始日期：" + TimeDialogUtil.getBeforeDay(0));
        mDropDownMenu.setDropDownMenu(list, popupViews, contentView);
        tvDateTo.setRightImageViewClickListener(l -> {
            tvDateTo.setCenterString("");
        });
        tvDateFrom.setRightImageViewClickListener(l -> {
            tvDateFrom.setCenterString("");
        });

    }
    
    //已处理
    private void initDoneRecycleView() {
        rvCheckReceivePakcageInfo.setLayoutManager(new LinearLayoutManager(getContext()));
        doneAsnPackageAdapter = new AsnPackageAdapter(doneAsnPackageBeanList);
        //  mRecyclerView.addItemDecoration(new RecycleViewDivider(getContext(), LinearLayoutManager.HORIZONTAL, R.drawable.item_drivide));
        doneAsnPackageAdapter.setOnItemClickListener((adapter, view, position) -> {
            if (position >= 0 && adapter.getData().size() > position) {
                doneAsnPackageAdapter.setCheckedPosition(position);

            }

        });
        rvCheckReceivePakcageInfo.setAdapter(doneAsnPackageAdapter);

    }

    private void queryData(){
        QueryListInput.Builder builder = new QueryListInput.Builder()
                .checkStatus("Y")
                .warehouseId(HttpClientHelper.getSelectWareHouse().getId())
                .isReject("Y")
                .isSelf("Y");
        switch (type){
            case PACKAGE_CHECK:
                break;
            case PACKAGE_PUTAWAY:
                builder.isPutaway("Y");
                break;

        }

        if (!tvDateFrom.getCenterTextView().getText().toString().isEmpty()) {
            builder.checkTimeFrom(tvDateFrom.getCenterString());

        }
        if (!tvDateTo.getCenterTextView().getText().toString().isEmpty()) {
           builder.checkTimeTo(tvDateTo.getCenterString());
        }
        mPresenter.queryAsnPackageList(builder.build()
               ,
                list -> {
                    doneAsnPackageAdapter.getData().clear();
                    doneAsnPackageAdapter.addData(list);
                    if(checkAsnPackageBean!=null){
                        scrollToPostion(checkAsnPackageBean);
                    }
                }

        );
    }
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(isVisibleToUser){
            queryData();
        }
    }

}
